<?php

class SearchDocController extends \BaseController {

	public function loadTemplate($id) {
		
		Log::info($id);
		
		$template = Template::find($id);
		
		return Response::json(['template' => $template, 'templateParams' => $template->templateParams]);
	}
	
	public function searchDocument() {
	
		$template_id = Input::get('template_id');
		
		$template = Template::find($template_id);
		
		$templateValues = array();
		foreach ($template->templateParams as $templateParam) {
			$template_param_value = Input::get('template_param_value_' . $templateParam->id);
			if ($template_param_value != '') {
				$templateValues = array_add($templateValues, $templateParam->id, $template_param_value);
			}
		}
					
		$results = DB::table('documents')
            ->join('document_index', 'documents.id', '=', 'document_index.document_id')
            ->join('templates', 'documents.template_id', '=', 'templates.id')
			->join('templateparams', function($join)
				{
					$join->on('templates.id', '=', 'templateparams.template_id')
						->On('document_index.template_param_id', '=', 'templateparams.id');
				})
            ->select('documents.id')
			->where('documents.template_id', '=', $template_id)
			->where(function($query) use ($templateValues) {
				foreach($templateValues as $key => $value) {
					$query->orwhere(function($query2) use ($key, $value) {
						
						$query2->where('document_index.template_param_id', '=', $key)
							->where('document_index.index_value', 'like', '%'.$value.'%');
					});
				}
			})
			->groupBy('id')
            ->get();
			
		$documents = array();
		if (count($results) > 0) {
			$documentIds = array();
			foreach($results as $result)
				$documentIds[] = $result->id;
				
			$documents = Document::whereIn('id', $documentIds)->paginate(10);
		}
				
		return View::make('tree.index')->with(['documents' => $documents]);
	}
}
